<?php

/**
 * 数据库操作类
 */
class MysqlDB {
	private $_host; // 主机地址
	private $_port; // 端口
	private $_username; // 用户名
	private $_password; // 密码
	private $_database; // 数据库
	private $_charset; // 编码
	private $_link; // 连接资源
	private $_result; // 结果集资源
	private static $instance; // 当前类的对象
	
	/**
	 * 获得单例对象的方法
	 * @return object
	 */
	public static function getInstance() {
		if (! (self::$instance instanceof self)) {
			self::$instance = new self ();
		}
		return self::$instance;
	}
	
	/**
	 * 防止对象被克隆
	 */
	private function __clone() {
	}
	
	/**
	 * 类的构造方法，可以传递一个数组参数，如果不传，使用配置文件默认值
	 * @param array $param 数据库参数数组     	
	 */
	private function __construct($param = array()) {
		$this->_host = isset ( $param ['host'] ) ? $param ['host'] : $GLOBALS ['config'] ['DB_HOST'];
		$this->_port = isset ( $param ['port'] ) ? $param ['port'] : $GLOBALS ['config'] ['DB_PORT'];
		$this->_username = isset ( $param ['username'] ) ? $param ['username'] : $GLOBALS ['config'] ['DB_USER'];
		$this->_password = isset ( $param ['password'] ) ? $param ['password'] : $GLOBALS ['config'] ['DB_PWD'];
		$this->_database = isset ( $param ['database'] ) ? $param ['database'] : $GLOBALS ['config'] ['DB_NAME'];
		$this->_charset = isset ( $param ['charset'] ) ? $param ['charset'] : $GLOBALS ['config'] ['DB_CHARSET'];
		$this->_connect ();
		$this->_select_db ();
		$this->_setcharset ();
	}
	
	/**
	 * 连接数据库服务器
	 */
	private function _connect() {
		$this->_link = mysql_connect ( $this->_host, $this->_username, $this->_password );
	}
	
	/**
	 * 选择数据库
	 */
	private function _select_db() {
		mysql_select_db ( $this->_database, $this->_link );
	}
	
	/**
	 * 设置编码格式
	 */
	private function _setcharset() {
		mysql_query ( 'set names ' . $this->_charset, $this->_link );
	}
	
	/**
	 * 发送sql语句
	 * @param string $query sql语句      	
	 */
	public function query($query) {
		$this->_result = mysql_query ( $query, $this->_link );
	}
	
	/**
	 * 获取结果集中的一行数据
	 * @return array
	 */
	public function fetch_assoc() {
		return mysql_fetch_assoc ( $this->_result );
	}
	
	/**
	 * 获取结果集总行数
	 * @return int
	 */
	public function num_rows() {
		return mysql_num_rows ( $this->_result );
	}
	
	/**
	 * 获取最后一次插入数据的id值
	 * @return int
	 */
	public function insert_id() {
		return mysql_insert_id ( $this->_link );
	}
	
	/**
	 * 获取受影响行数
	 * @return int
	 */
	public function affected_rows() {
		return mysql_affected_rows ( $this->_link );
	}
	
	/**
	 * 关闭连接资源
	 */
	private function _close() {
		mysql_close ( $this->_link );
	}
	
	/**
	 * 析构函数
	 */
	public function __destruct() {
		$this->_close();
	}
}